package com.enba.boot.security.jwt;

import com.enba.boot.core.base.Result;
import com.enba.boot.redis.RedisOperator;
import com.enba.boot.security.properties.SecurityRedisKeyProperties;
import com.enba.boot.security.vo.UserToken;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/** 登录成功处理器 */
public class DefaultJwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  private final JwtTokenUtils jwtTokenUtils;
  private final RedisOperator redisOperator;
  private final SecurityRedisKeyProperties redisKeyProperties;

  public DefaultJwtAuthenticationSuccessHandler(
      JwtTokenUtils jwtTokenUtils,
      RedisOperator redisOperator,
      SecurityRedisKeyProperties redisKeyProperties) {
    this.jwtTokenUtils = jwtTokenUtils;
    this.redisOperator = redisOperator;
    this.redisKeyProperties = redisKeyProperties;
  }

  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException {
    JwtUserDetails userDetails = (JwtUserDetails) authentication.getPrincipal();

    // 生成token令牌
    Map<String, Object> claims = new HashMap<>();
    claims.put("userKey", userDetails.getUsername());
    String token = jwtTokenUtils.generateToken(claims);

    // 设置用户信息，角色信息，权限信息到redis
    redisOperator.set(
        redisKeyProperties.getRoleKey() + userDetails.getUsername(),
        userDetails.getRoleList(),
        redisKeyProperties.getExpire());

    redisOperator.set(
        redisKeyProperties.getUserKey() + userDetails.getUsername(),
        userDetails.getUser(),
        redisKeyProperties.getExpire());

    redisOperator.set(
        redisKeyProperties.getPermissionKey() + userDetails.getUsername(),
        userDetails.getPermissionList(),
        redisKeyProperties.getExpire());

    Result.render(
        response, Result.success(new UserToken().setUser(userDetails.getUser()).setToken(token)));
  }
}
